package domain.weapon;

import java.awt.Color;

import sounds.Sounds;

import com.uqbar.vainilla.DeltaState;
import com.uqbar.vainilla.appearances.Circle;
import components.CircularShape;
import components.Shape;
import domain.components.WormsComponent;
import domain.game.BattleManager;
import domain.game.GameState;
import domain.game.KeysHandler;

public class Projectile extends WormsComponent {

	private double angle;
	private double vx;
	private double vy;
	private double time;
	private Explosion explosion;
	private int dir;
	private int cuentaRegresiva;

	
	private double t1 = 0;
	private double t2 = 0;

	public Projectile(int dir, int aDiameter, int aHeight, double x, double y, Explosion explosion,double speed, double angle, int cuentaRegresiva) {
		super(aDiameter, aHeight, x-(aDiameter/2)+25, y-(aDiameter/2)+25);
		this.time = 0;
		this.dir = dir;
		this.explosion = explosion;
		this.cuentaRegresiva = cuentaRegresiva;
		
		this.angle = Math.toRadians(angle+((-this.dir)*90));
		
		this.vx = speed  * Math.cos(this.angle);
		this.vy = speed * Math.sin(this.angle);
		
		this.setAppearance(new Circle(Color.green, aDiameter));
	}
	
	public double getYdif(){
		return (this.vy) + (2*time*time*0.5);
	}
	
	@Override
	public boolean isSolid() {
		return false;
	}
	

	@Override
	protected void onCollisionWithSolid(WormsComponent gc) {
		this.explode();
	}

	private synchronized void explode() {

		if (this.isEnable()){

			//Nose si esta bien!
			if(t1+ this.cuentaRegresiva == t2){
				this.setEnable(false);
				this.getScene().explosionOn(this.getExplosion());
				this.destroyComponent();
				//this.gs.getKeysHandler().getScene().changeTurn();
				this.getScene().changeTurn();
				
				//sonido de explosion
				(Sounds.sounds.get("explosion")).play();
				
			}else{
				t2++;
				(Sounds.sounds.get("time")).play();
			}
			//sonido de timepo de explosion
		}
	}

	protected Explosion getExplosion() {
		this.explosion.centerOn((int)this.getX(), (int)this.getY());
		return this.explosion;
	}

	@Override
	protected void defineCollide(WormsComponent gc) {
		gc.collideWithProyectile(this);
	}

	
	protected void effectiveUpdate(DeltaState deltaState) {
		
		
		this.time += deltaState.getDelta();
		
		
		double xdif, ydif;
		xdif = ((deltaState.getDelta() * this.vx));
		ydif = (deltaState.getDelta() * (this.vy)) + (2*time*time*0.5);
		
		
		if (!this.collide(this.getX()+xdif, this.getY() + ydif)){
			if(!this.getScene().getTerrain().isCollision(this.getX()+xdif, this.getY()+ydif, this.getDiameter(), this.getHeight())){
				this.updateCoords(xdif, ydif);
			}else{
				this.explode();
			}
				
		
		}
		this.time += deltaState.getDelta();
	}

	@Override
	public Shape defineShape() {
		return new CircularShape(this);
	}

}
